package com.web.cms.ad.provider;

import com.blue.integration.serve.StorageClient;
import com.blue.jdbc.Page;
import com.blue.validation.ValidationUtil;
import com.blue.validation.group.SaveModel;
import com.blue.validation.group.UpdateModel;
import com.web.cms.ad.cache.AdvCache;
import com.web.cms.ad.exception.AdvException;
import com.web.cms.ad.facade.AdvFacade;
import com.web.cms.ad.message.AdvRequest;
import com.web.cms.ad.message.AdvResponse;
import com.web.cms.ad.model.Adv;
import com.web.cms.ad.service.AdvService;
import com.web.cms.ad.util.AdvConvertor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 广告接口实现类
 * 
 * @author 代码由 blue-code 框架生成
 * @since 1.0 2017年11月13日
 */
@Component("adAdvProvider")
public class AdvProvider implements AdvFacade
{
	@Autowired
	private AdvService advService;
	@Autowired
	private AdvCache advCache;
	@Autowired
	private StorageClient storageClient;
	
	public AdvProvider()
	{
	}

	@Override
	public AdvResponse add(AdvRequest request)
	{
		ValidationUtil.valid(request, SaveModel.class);
		Adv adv = AdvConvertor.toAdv(request);
		adv = advService.save(adv);
		advCache.delete();
		AdvResponse response = AdvConvertor.toResponse(adv, storageClient);
		return response;
	}

	@Override
	public AdvResponse update(AdvRequest request)
	{
		ValidationUtil.valid(request, UpdateModel.class);
		Adv adv = AdvConvertor.toAdv(request);
		adv = advService.save(adv);
		advCache.delete();
		AdvResponse response = AdvConvertor.toResponse(adv, storageClient);
		return response;
	}

	@Override
	public AdvResponse get(Integer id)
	{
		if (id == null)
			throw new AdvException("Id不能为空");
			
		Adv adv = advCache.get(id);
		AdvResponse response = AdvConvertor.toResponse(adv, storageClient);
		return response;
	}

	@Override
	public Page<AdvResponse> listPage(AdvRequest request, int start, int size)
	{
		Adv adv = AdvConvertor.toAdv(request);
		Page<Adv> page = new Page<>(size);
		page.setCurPage(start);
		page = advService.list(adv, page);
		Page<AdvResponse> pageResponse = AdvConvertor.toResponse(page, storageClient);
		return pageResponse;
	}

	@Override
	public List<AdvResponse> listAdv(Integer webId, String code)
	{
		List<Adv> list = advCache.listByWeb(webId, code);
		List<AdvResponse> responseList = AdvConvertor.toResponse(list, storageClient);
		return responseList;
	}

	@Override
	public List<AdvResponse> listAdvByCode(String webCode, String code)
	{
		List<Adv> list = advCache.listByWeb(webCode, code);
		List<AdvResponse> responseList = AdvConvertor.toResponse(list, storageClient);
		return responseList;
	}

	@Override
	public void refresh()
	{
		advCache.delete();
	}

}
